﻿using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Configuration;
using System.Net.Mail;
using System.Net.Sockets;
using System.Text;
using System.Web;
using System.Web.Configuration;
using System.Web.UI;
using System.Web.UI.WebControls;
using WeeklyEmailReporting;

public partial class WeeklyProgressReport : BasePage
{
	protected void Page_Load(object sender, EventArgs e)
	{
		if (!IsPostBack)
		{
			try
			{
				string connectionString = ConfigurationManager.ConnectionStrings["MainConnectionString"].ConnectionString;
				string message;
				string studentId = Request.Params["studentId"];
				string id = Request.Params["id"];

				byte[] pdfBytes = new byte[1];

				if (Request.Params["reportType"] == "0")
				{
					//get latest sent progress report

					DataTable dt = DataLayer.GetWeeklyProgressReportBody(connectionString, Convert.ToDecimal(id), out message);
					if (dt.Rows.Count > 0)
						if (dt.Rows[0]["BODY"] != DBNull.Value)
							pdfBytes = (byte[]) dt.Rows[0]["BODY"];
				}

				if (Request.Params["reportType"] == "1")
				{
					//get current weekly progress report
					DataSet ds = DataLayer.GetEmailingWeeklyProgressReport(connectionString, Convert.ToDecimal(studentId), out message);

					string htmlReport = "";
					if (ds.Tables.Count == 2)
					{
						if (ds.Tables[0].Rows.Count > 0)
						{
							DataRow studentRow = ds.Tables[0].Rows[0];
							htmlReport = HtmlTemplateUtility.GetHtmlReportFromTemplate(ds.Tables[0].Rows[0], ds.Tables[1]);
						}
					}

					/*
					 * Converting HTML to PDF
					 *
					 */
					string converter = Server.MapPath("~/wkhtmltopdf/wkhtmltopdf.exe");
					string htmlFileName = Server.MapPath("~/WeeklyReportFiles/" + studentId + ".html");
					string pdfFileName = Server.MapPath("~/WeeklyReportFiles/" + studentId + ".pdf");

					File.WriteAllText(htmlFileName, htmlReport);
					ProcessStartInfo psi = new ProcessStartInfo(converter, string.Format("\"{0}\" \"{1}\"", htmlFileName, pdfFileName))
					                       	{
					                       		UseShellExecute = false,
					                       		CreateNoWindow = true
					                       	};
					using (Process process = Process.Start(psi))
					{
						process.WaitForExit(60000);
					}

					pdfBytes = File.ReadAllBytes(pdfFileName);


					//pdfBytes = Html2Pdf.Convert(htmlReport).GetBuffer();

					//ReportViewer1.LocalReport.SetParameters(new ReportParameter("reportHtml", htmlReport.Replace("\r", "").Replace("\n", "").Replace("\t", "")));

					//Warning[] warnings;
					//string[] streamids;
					//string mimeType;
					//string encoding;
					//string filenameExtension;

					//pdfBytes = ReportViewer1.LocalReport.Render(
					//    "PDF", null, out mimeType, out encoding, out filenameExtension,
					//    out streamids, out warnings);

				}

				if (pdfBytes.Length == 1)
				{
					Response.Write(string.Format("There aren't sent Weekly Progress Report for studentId = {0}.",
					                             Request.Params["studentId"]));
					Response.End();
				}
				else
				{
					Response.ContentType = "application/pdf";
					Response.OutputStream.Write(pdfBytes, 0, pdfBytes.Length);
					Response.Flush();
					Response.Close();
				}
			}
			catch(Exception ex)
			{
				//Response.Write("Unexpected error occured. Please contact technical support for assistance.");
                Response.Write(ex.Message);
			}
		}

	}

}